package com.cff.pm.client;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;

import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;

public class ClinetCookieJar implements CookieJar{
	private final static Map<String, Map<String, List<Cookie>>> cookieStores = new HashMap<String, Map<String, List<Cookie>>>();
	String key;
	public ClinetCookieJar(String key) {
		this.key = key;
	}

	@Override
	public void saveFromResponse(HttpUrl httpUrl, List<Cookie> list) {
		Map<String, List<Cookie>> mapsCookie = cookieStores.get(key);
		if (mapsCookie == null){
			mapsCookie = new HashMap<>();
			cookieStores.put(key, mapsCookie);
		}
		List<Cookie> cookies = mapsCookie.get(httpUrl.host());
		if (cookies == null)
			cookies = new ArrayList<Cookie>();
		LinkedHashSet<Cookie> set = new LinkedHashSet<Cookie>();
		set.addAll(cookies);
		if (list != null)
			set.addAll(list);
		cookies.clear();
		cookies.addAll(set);
		mapsCookie.put(httpUrl.host(), cookies);
	}

	@Override
	public List<Cookie> loadForRequest(HttpUrl httpUrl) {
		Map<String, List<Cookie>> mapsCookie = cookieStores.get(key);
		if(mapsCookie == null)return new ArrayList<Cookie>();
		List<Cookie> cookies = mapsCookie.get(httpUrl.host());				
		return cookies != null ? cookies : new ArrayList<Cookie>();
	}

}
